﻿using System;
using System.Collections.Generic;

namespace InDepth2Demo.Chapter8
{
    /// <summary>
    /// 8.3 简化的初始化
    /// </summary>
    public class SimplifiedInitialization
    {
        public static void Call()
        {
            // C# 1 代码
            Person tom1 = new Person();
            tom1.Name = "Tom";
            tom1.Age = 9;

            // C# 3 代码
            Person person1 = new Person() { Name = "Tom", Age = 6 };
            Person person2 = new Person { Name = "Tom", Age = 6 };

            // 在每一行的末尾，用大括号括的就是对象初始化程序。
            // person1 和 person2 的 IL 是完全一样的。且与 tom1 也是一样的


            // 为嵌入对象设置属性
            // C# 1 代码
            person1.Home.Country = "China";

            // C# 3 代码
            Person tom2 = new Person("Tom")
            {
                Name = "Tom2",
                Age = 9,
                Home = { Country = "UK", Town = "Reading" }
            };
            Console.WriteLine(tom2.Name);

            // 数组的对象初始化程序
            Person[] family = new Person[]
            {
                new Person { Name = "Holly", Age = 34 }
            };

        }
    }

    class Person
    {
        public int Age { get; set; }
        public string Name { get; set; }

        public Person() { }

        public Person(string name)
        {
            Name = name;
        }

        List<Person> friends = new List<Person>();
        public List<Person> Friends
        {
            get { return friends; }
        }

        Location home = new Location();
        public Location Home
        {
            get { return home; }
        }
    }

    public class Location
    {
        public string Country { get; set; }
        public string Town { get; set; }
    }

}
